import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartItems: [],
    products: [
      { id: 1, name: '手机', price: 1000 },
      { id: 2, name: '电脑', price: 2000 },
      { id: 3, name: '键盘', price: 100 },
      { id: 4, name: '鼠标', price: 50 }
    ]
  },
  getters: {
    totalPrice: state => {
      return state.cartItems.reduce((total, item) => {
        return total + item.price * item.quantity
      }, 0)
    },
    cartItemCount: state => {
      return state.cartItems.reduce((count, item) => {
        return count + item.quantity
      }, 0)
    }
  },
  mutations: {
    addToCart(state, product) {
      const existingItem = state.cartItems.find(item => item.id === product.id)
      if (existingItem) {
        existingItem.quantity++
      } else {
        state.cartItems.push({ ...product, quantity: 1 })
      }
    },
    removeFromCart(state, productId) {
      const index = state.cartItems.findIndex(item => item.id === productId)
      if (index !== -1) {
        if (state.cartItems[index].quantity > 1) {
          state.cartItems[index].quantity--
        } else {
          state.cartItems.splice(index, 1)
        }
      }
    }
  },
  actions: {
    addToCart({ commit }, product) {
      commit('addToCart', product)
    },
    removeFromCart({ commit }, productId) {
      commit('removeFromCart', productId)
    }
  },
  modules: {
  }
})